package com.cr.dataprotect.sdk;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cr.dataprotect.entity.IntegrityEntity;
import org.apache.ibatis.jdbc.SqlRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 默认获取完整性保护数据
 * 使用从表中查询的方式，可重新实现该接口
 */
@Service
public class DefaultIntegrityApiImpl  implements IntegrityApi {

    private static final String selectSql = "select integrity_data from %s where data_id = '%s' and table_name = '%s'";
    private static final String insertSql = "insert into %s (data_id, table_name, in_data, integrity_data) values ('%s', '%s', '%s', '%s')";
    private static final String updateSql = "update %s set in_data = '%s', integrity_data = '%s' where data_id = '%s' and table_name = '%s'";
    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public String getIntegrityData(String dataId, String tableName, String saveTable) {
        String formattedSql = String.format(selectSql, saveTable, dataId, tableName);
        List<Map<String, Object>> list = executeRawSQL(formattedSql);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            return list.get(0).get("INTEGRITY_DATA").toString();
        }
    }

    @Override
    public void saveIntegrityData(String dataId, String indata, String integrityData, String tableName, String saveTable) {
        String formattedSql = String.format(insertSql, saveTable, dataId, tableName, indata, integrityData);
        runSQL(formattedSql);
    }

    @Override
    public void updateIntegrityData(String dataId, String indata, String integrityData, String tableName, String saveTable) {
        String formattedSql = String.format(updateSql, saveTable, indata, integrityData, dataId, tableName);
        runSQL(formattedSql);
    }


    private List<Map<String, Object>> executeRawSQL(String sql, Object... params) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            Connection conn = sqlSession.getConnection();
            SqlRunner sqlRunner = new SqlRunner(conn);

            // 执行查询（自动处理参数化）
            try {
                return sqlRunner.selectAll(sql, params); // params 自动转 PreparedStatement 参数
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void runSQL(String sql) {
        try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
            Connection conn = sqlSession.getConnection();
            SqlRunner sqlRunner = new SqlRunner(conn);
            try {
                sqlRunner.run(sql);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
